#pragma once
#include "LuaObjMacro.h"

#ifdef USE_NED_MALLOC
#include "malloc/nedmalloc.h"
#endif

#undef malloc
#undef free
#undef realloc
#undef calloc

#ifdef NEDMALLOC_H
typedef nedpool* mempoll_t;

#define mempollcreate nedcreatepool
#define mempolldestroy neddestroypool
#define mempollmalloc nedpmalloc
#define mempollrealloc nedprealloc
#define mempollfree nedpfree
#define mempoll_calloc nedpcalloc
#elif DLMALLOC_VERSION
#include "../malloc/dlmalloc.h"
typedef mspace mempoll_t;
#define mempollcreate create_mspace
#define mempolldestroy destroy_mspace
#define mempollmalloc mspace_malloc
#define mempollrealloc mspace_realloc
#define mempollfree mspace_free
#define mempoll_calloc mspace_calloc
#endif

#ifdef USE_NED_MALLOC
#define USE_MEM_POLL
#endif

class LUAOBJ_API LuaMemPool
{
public:
	LuaMemPool(size_t defSize,bool useLock)
	{
#ifdef USE_MEM_POLL
		m_pool = mempollcreate(defSize, useLock);
#endif
	}

	~LuaMemPool(void)
	{
#ifdef USE_MEM_POLL
		mempolldestroy(m_pool);
#endif
	}


	inline void* malloc(size_t bytes)
	{
#ifdef USE_MEM_POLL
		return mempollmalloc(m_pool, bytes);
#else
		return ::malloc(bytes);
#endif
	}

	inline void free(void* mem)
	{
#ifdef USE_MEM_POLL
		mempollfree(m_pool, mem);
#else
		return ::free(mem);
#endif
	}

	inline void* realloc(void* mem, size_t newsize)
	{
#ifdef USE_MEM_POLL
		return mempollrealloc(m_pool, mem, newsize);
#else
		return ::realloc(mem, newsize);
#endif
	}

	inline void* calloc(size_t n_elements, size_t elem_size)
	{
#ifdef USE_MEM_POLL
		return mempoll_calloc(m_pool, n_elements, elem_size);
#else
		return ::calloc(n_elements, elem_size);
#endif
	}
private:
#ifdef USE_MEM_POLL
	mempoll_t m_pool;
#endif
};

